<template>
  <div>
    <div class="clearfix review-btn-warp">
      <el-button
        icon="ele-Check"
        type="success"
        v-if="showBtn('agree')"
        @click="handleComplete"
      >
        {{ $t("formI18n.all.agree") }}
      </el-button>
      <el-button
        icon="ele-RefreshLeft"
        type="warning"
        @click="handleReturn"
        v-if="showBtn('return')"
      >
        {{ $t("formI18n.all.return") }}
      </el-button>
      <el-button
        icon="ele-Close"
        type="danger"
        v-if="showBtn('reject')"
        @click="handleReject"
      >
        {{ $t("formI18n.all.refuse") }}
      </el-button>
      <el-button
        icon="ele-Position"
        @click="handleTransfer"
        v-if="showBtn('transfer')"
      >
        {{ $t("formI18n.all.transfer") }}
      </el-button>
      <el-button
        icon="ele-User"
        @click="handleDelegate"
        v-if="showBtn('delegate')"
      >
        {{ $t("formI18n.all.delegate") }}
      </el-button>
      <el-button
        icon="ele-DArrowLeft"
        @click="handleAddSign('BEFORE_ADD_SIGN')"
        v-if="showBtn('addSignBefore')"
      >
        {{ $t("formI18n.all.addSignBefore") }}
      </el-button>
      <el-button
        icon="ele-DArrowRight"
        @click="handleAddSign('AFTER_ADD_SIGN')"
        v-if="showBtn('addSignAfter')"
      >
        {{ $t("formI18n.all.addSignAfter") }}
      </el-button>
      <el-button
        style="float: right"
        icon="ele-Back"
        type="primary"
        @click="goBack(true)"
        v-if="!simpleReview"
      >
        {{ $t("formI18n.all.goBack") }}
      </el-button>
    </div>
    <!--退回流程-->
    <basic-audit-task-form
      :title="$t('formI18n.all.return')"
      v-model:show="returnOpen"
      :label="$t('workflow.flowDetail.agreeOpinions')"
      :comment-label="$t('workflow.flowDetail.transferOpinions')"
      :default-form="taskForm"
      @submit="taskReturn"
    >
      <template #alert>
        <el-alert
          :title="$t('workflow.flowDetail.returnTitle')"
          type="success"
          show-icon
          :closable="false"
          class="mb20"
        />
      </template>
      <template #form>
        <el-form-item
          :label="$t('workflow.flowDetail.returnNode')"
          prop="targetKey"
        >
          <el-radio-group v-model="taskForm.targetKey">
            <el-radio-button
              v-for="item in returnTaskList"
              :key="item.taskDefinitionKey"
              :value="item.taskDefinitionKey"
            >
              {{ item.name }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
      </template>
    </basic-audit-task-form>
    <!--审批正常流程-->
    <basic-audit-task-form
      :title="$t('formI18n.all.agree')"
      v-model:show="completeOpen"
      :label="$t('workflow.flowDetail.agreeOpinions')"
      :comment-label="$t('workflow.flowDetail.agreeOpinions')"
      :default-form="taskForm"
      @submit="taskComplete"
    >
      <template #alert>
        <el-alert
          :title="$t('workflow.flowDetail.agreeText')"
          type="success"
          show-icon
          :closable="false"
          class="mb20"
        />
      </template>
    </basic-audit-task-form>
    <!--拒绝-->
    <basic-audit-task-form
      :title="$t('formI18n.all.refuse')"
      v-model:show="rejectOpen"
      :label="$t('workflow.flowDetail.agreeOpinions')"
      :comment-label="$t('workflow.flowDetail.refuseOpinions')"
      :default-form="taskForm"
      @submit="taskReject"
    >
      <template #alert>
        <el-alert
          :title="$t('workflow.flowDetail.refuseTitle')"
          type="error"
          show-icon
          :closable="false"
          class="mb20"
        />
      </template>
    </basic-audit-task-form>
    <!--转办流程-->
    <basic-audit-task-form
      :title="$t('formI18n.all.transfer')"
      v-model:show="transferOpen"
      :label="$t('workflow.flowDetail.agreeOpinions')"
      :comment-label="$t('workflow.flowDetail.transferOpinions')"
      :default-form="taskForm"
      @submit="taskTransfer"
    >
      <template #alert>
        <el-alert
          :title="$t('workflow.flowDetail.transferText')"
          type="error"
          show-icon
          :closable="false"
          class="mb20"
        />
      </template>
      <template #form>
        <el-form-item
          :label="$t('workflow.flowDetail.transactors')"
          prop="newAssignee"
          :rules="[{ required: true, message: '', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.newAssignee"
            readonly
            :placeholder="$t('workflow.flowDetail.selectTransactors')"
            @click="handleOpenUserSelect(false)"
          />
        </el-form-item>
      </template>
    </basic-audit-task-form>

    <!--    委派-->
    <basic-audit-task-form
      :title="$t('formI18n.all.delegate')"
      v-model:show="delegateOpen"
      :label="$t('workflow.flowDetail.agreeOpinions')"
      :comment-label="$t('workflow.flowDetail.delegateOpinions')"
      :default-form="taskForm"
      @submit="taskDelegate"
    >
      <template #alert>
        <el-alert
          :title="$t('workflow.flowDetail.delegateText')"
          type="error"
          show-icon
          :closable="false"
          class="mb20"
        />
      </template>
      <template #form>
        <el-form-item
          :label="$t('workflow.flowDetail.delegateUser')"
          prop="newAssignee"
          :rules="[{ required: true, message: $t('workflow.flowDetail.selectDelegateUser'), trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.newAssignee"
            readonly
            :placeholder="$t('workflow.flowDetail.selectDelegateUser')"
            @click="handleOpenUserSelect(false)"
          />
        </el-form-item>
      </template>
    </basic-audit-task-form>

    <!--    前加签-->
    <basic-audit-task-form
      :title="$t('workflow.flowDetail.addSign')"
      v-model:show="addSignOpen"
      :label="$t('workflow.flowDetail.agreeOpinions')"
      :comment-label="$t('workflow.flowDetail.addSignOpinions')"
      :default-form="taskForm"
      @submit="taskAddSign"
    >
      <template #alert>
        <el-alert
          v-if="taskForm.addSignType === 'AFTER_ADD_SIGN'"
          :title="$t('workflow.flowDetail.afterSignText')"
          type="error"
          show-icon
          :closable="false"
          class="mb20"
        />
        <el-alert
          v-if="taskForm.addSignType === 'BEFORE_ADD_SIGN'"
          :title="$t('workflow.flowDetail.beforeSignText')"
          type="error"
          show-icon
          :closable="false"
          class="mb20"
        />
      </template>
      <template #form>
        <el-form-item
          :label="$t('workflow.flowDetail.transactors')"
          prop="assignees"
          :rules="[{ required: true, message: $t('workflow.flowDetail.selectTransactors'), trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.assignees"
            readonly
            :placeholder="$t('workflow.flowDetail.selectTransactors')"
            @click="handleOpenUserSelect(true)"
          />
        </el-form-item>
      </template>
    </basic-audit-task-form>
    <!--    用户单选-->
    <user-choose-table
      ref="userChooseTableRef"
      :multiple="false"
      @submit="
        val => {
          handleSelectUser(val, 'newAssignee');
        }
      "
    />
    <!--     多选-->
    <user-choose-table
      ref="userMulChooseTableRef"
      @submit="
        val => {
          handleSelectUser(val, 'assignees');
        }
      "
    />
  </div>
</template>

<script setup lang="ts">
import { inject, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import UserChooseTable from "@/views/system/user/chooseTable.vue";
import BasicAuditTaskForm from "./components/BasicAuditTaskForm.vue";
import { addSignTask, complete, delegateTask, rejectTask, returnList, returnTask, transferTask } from "@/api/workflow/todo";
import { closeCurrentTag } from "@/utils/other";
import { i18n } from "@/i18n";
import { MessageUtil } from "@/utils/messageUtil";
import { ElLoading } from "element-plus";
import { handleProcessFunc } from "@/views/workflow/task/process/hooks/useHandleProcess";
import { isWxEnv, isWxMiniEnv } from "@/views/form/write/hooks/wx";
import loadWXJs from "@/views/formgen/utils/loadWxSdk";

// Props
const props = defineProps({
  // 获取
  getFormDataId: {
    type: Function,
    default: () => {
      return Function;
    }
  },
  getFormModel: {
    type: Function,
    default: () => {
      return Function;
    }
  },
  taskInfo: {
    type: Object,
    default: () => {
      return {};
    }
  },
  simpleReview: {
    type: Boolean,
    default: false
  }
});

// Emits
const emit = defineEmits(["change"]);

// Router
const router = useRouter();
const route = useRoute();

// Reactive state
const returnTaskList = ref<any[]>([]);
const completeOpen = ref(false);
const rejectOpen = ref(false);
const transferOpen = ref(false);
const addSignOpen = ref(false);
const delegateOpen = ref(false);
const returnOpen = ref(false);

const taskForm = reactive<any>({
  comment: "",
  instanceId: "",
  deployId: "",
  taskId: "",
  procDefId: "",
  vars: {},
  targetKey: "",
  newAssignee: "",
  addSignType: "",
  assignees: ""
});

// Watch for taskInfo prop changes
watch(
  () => props.taskInfo,
  newTaskInfo => {
    Object.assign(taskForm, newTaskInfo);
  },
  { deep: true, immediate: true }
);

// Methods
const handleComplete = () => {
  completeOpen.value = true;
  handleResetForm();
};

const checkFormValidateStatus = inject<Function>("checkFormValidateStatus");

const taskComplete = async (form: any) => {
  // if (!form.comment) {
  //   MessageUtil.error(i18n.global.t("workflow.flowDetail.enterOpinions"));
  //   return;
  // }
  const checkStatus = await checkFormValidateStatus();
  if (!checkStatus) {
    return;
  }
  startElLoading();
  const data = {
    ...form,
    values: props.getFormModel(),
    formDataId: props.getFormDataId()
  };
  complete(data)
    .then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      completeOpen.value = false;
      emit("change");
      goBack();
    })
    .catch(() => {})
    .finally(() => {
      closeLoading();
    });
};

const handleReject = () => {
  handleResetForm();
  rejectOpen.value = true;
};

const handleDelegate = () => {
  handleResetForm();
  delegateOpen.value = true;
};

const taskReject = (form: any) => {
  const data = {
    ...form,
    values: props.getFormModel(),
    formDataId: props.getFormDataId()
  };
  startElLoading();
  rejectTask(data)
    .then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      rejectOpen.value = false;
      goBack();
    })
    .finally(() => {
      closeLoading();
    });
};

const handleTransfer = () => {
  handleResetForm();
  transferOpen.value = true;
};

const taskTransfer = (form: any) => {
  const data = {
    ...form,
    values: props.getFormModel(),
    formDataId: props.getFormDataId()
  };
  startElLoading();
  transferTask(data)
    .then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      goBack();
    })
    .finally(() => {
      closeLoading();
    });
};

const taskDelegate = (form: any) => {
  const data = {
    ...form,
    values: props.getFormModel(),
    formDataId: props.getFormDataId()
  };
  startElLoading();
  delegateTask(data)
    .then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      goBack();
    })
    .finally(() => {
      closeLoading();
    });
};

const handleAddSign = (type: string) => {
  addSignOpen.value = true;
  handleResetForm();
  taskForm.addSignType = type;
};

const taskAddSign = (form: any) => {
  const data = {
    ...form,
    values: props.getFormModel(),
    formDataId: props.getFormDataId(),
    assigneeList: taskForm.assignees.split(",")
  };
  startElLoading();
  addSignTask(data)
    .then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      goBack();
    })
    .finally(() => {
      closeLoading();
    });
};

const handleResetForm = () => {
  taskForm.comment = "";
  taskForm.addSignType = "";
  taskForm.assignees = "";
  taskForm.newAssignee = "";
  taskForm.targetKey = "";
};

const handleReturn = () => {
  returnOpen.value = true;
  handleResetForm();
  returnList(taskForm).then((res: any) => {
    returnTaskList.value = res.data;
    if (res.data && res.data[0]) {
      taskForm.targetKey = res.data[0].taskDefinitionKey;
    }
    taskForm.values = null;
  });
};

const taskReturn = (form: any) => {
  startElLoading();
  const data = {
    ...form,
    values: props.getFormModel(),
    formDataId: props.getFormDataId()
  };
  returnTask(data)
    .then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      goBack();
    })
    .finally(() => {
      closeLoading();
    });
};

const userMulChooseTableRef = ref<any>(null);
const userChooseTableRef = ref<any>(null);

const handleOpenUserSelect = (mul: boolean) => {
  if (mul) {
    userMulChooseTableRef.value.showDialog([]);
  } else {
    userChooseTableRef.value.showDialog([]);
  }
};

const handleSelectUser = (val: any, key: string) => {
  if (val) {
    taskForm[key] = val.map((item: any) => item.userName).join(",");
  }
};

let loading: any = null;

const startElLoading = () => {
  loading = ElLoading.service({
    lock: true,
    text: "审批处理中",
    background: "rgba(0, 0, 0, 0.7)"
  });
};

const closeLoading = () => {
  loading.close();
};

const { operationBtnList } = handleProcessFunc;

const goBack = (backBtn = false) => {
  const previousRoute = router.currentRoute.value;
  closeCurrentTag(route);
  router.go(-1);
  if (isWxEnv()) {
    loadWXJs(wx => {
      isWxMiniEnv().then(res => {
        // 看到提示再走
        setTimeout(
          () => {
            wx.miniProgram.navigateBack();
          },
          backBtn ? 1 : 500
        );
      });
    });
  }
  setTimeout(() => {
    if (router.currentRoute.value.fullPath === previousRoute.fullPath) {
      console.log("后退失败，停留在当前页面");
      router.push({ path: "/workflow/todo" });
    }
  }, 500);
};

// 是否显示按钮
const showBtn = (name: string) => {
  // 小程序使用的简单审批模式
  if (props.simpleReview && !["agree", "reject"].includes(name)) {
    return false;
  }
  // 兼容老的数据 之前没这个字段的时候默认显示
  if (!operationBtnList.value || !operationBtnList.value.length) {
    return true;
  }
  return operationBtnList.value!.includes(name);
};
</script>

<style lang="scss" scoped>
.review-dialog {
  width: 45%;
  margin: 0 auto;
  z-index: 9999;
}

@media screen and (max-width: 992px) {
  .review-dialog {
    width: 100% !important;
  }
}
</style>
